package weaver.formmode.interfaces.dmlaction.commands.actions;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.api.formmode.cache.ModeComInfo;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.engine.cube.biz.ShardingActionHelper;
import com.engine.cube.biz.ShardingHelper;
import com.engine.cube.util.AddSeclevelUtil;
import com.engine.cube.util.SaveConditionUtil;
import com.google.common.base.Strings;
import com.sun.jdi.PathSearchingVirtualMachine;
import com.weaver.formmodel.util.StringHelper;
import org.apache.commons.beanutils.BeanUtils;

import com.weaver.formmodel.util.DateHelper;

import org.apache.commons.collections.map.HashedMap;
import weaver.conn.ConnStatement;
import weaver.conn.ConnStatementDataSource;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.data.ModeDataIDUpdateSingle;
import weaver.formmode.data.ModeDataIdUpdate;
import weaver.formmode.exttools.impexp.db.DatabaseUtils;
import weaver.formmode.interfaces.dmlaction.DBTypeUtil;
import weaver.formmode.log.FormmodeLog;
import weaver.formmode.service.CommonConstant;
import weaver.formmode.setup.ModeRightInfo;
import weaver.formmode.virtualform.UUIDPKVFormDataSave;
import weaver.formmode.virtualform.VirtualFormHandler;
import weaver.general.StringUtil;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Cell;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.Row;

import weaver.workflow.workflow.WorkflowBillComInfo;

public class DMLAction extends FormmodeLog implements Action
{
	// CHANGE START
	private static final String PATTERN_TABLE = "(update|insert\\s*into|delete\\s*from)\\s*(\\b\\w*\\b)\\s*";
	// CHANGE END
	private int expandid;
	private int modeid;
	private int actionid;
	private int detailid;
	private boolean isCardSubmit=false;
	private int creator = 1;
	private User user;
    private List<Property[]> propertiesList = new ArrayList<Property[]>();
	/**
	 * dml接口执行结果
	 */
	private Map<String, String> dmlResult = new HashMap<String, String>();
	public void setIsCardSubmit(boolean iscardSubmit){
		this.isCardSubmit=iscardSubmit;
	}
	public boolean getIsCardSubmit(boolean iscardSubmit){
		return this.isCardSubmit;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public int getActionid() {
		return actionid;
	}
	public void setActionid(int actionid) {
		this.actionid = actionid;
	}
	public int getDetailid() {
		return detailid;
	}
	public void setDetailid(int detailid) {
		this.detailid = detailid;
	}
	public int getExpandid() {
		return expandid;
	}
	public void setExpandid(int expandid) {
		this.expandid = expandid;
	}
	public int getModeid() {
		return modeid;
	}
	public void setModeid(int modeid) {
		this.modeid = modeid;
	}

	public Map<String, String> getDmlResult() {
		return dmlResult;
	}
	/**
	 * 执行dmlaction
	 */
	public String execute(RequestInfo request)
	{
		dmlResult.put("flag", "true");
		creator = Util.getIntValue(request.getLastoperator(),1);
		if(creator<=0){
			creator = 1;
		}
		try
		{

			RecordSetTrans rst = request.getRsTrans();
			RecordSet rs = new RecordSet();
			//获取dmlaction 属性
			List dmlList = this.getDmlActionSet(rst, rs);

			writeLog("获取dmlaction 属性 dmlList : "+dmlList.size());

			Property[] properties = request.getMainTableInfo().getProperty();// 获取表单主字段信息
			//添加固定字段的值
			properties = addSpecialFieldValue(properties,request);
			if(dmlList.size()>0)
			{
				String fieldname = "";
				List fieldtypeList = new ArrayList();
				List fieldnameList = new ArrayList();
				List fieldvalueList = new ArrayList();
				List sqlsetList = new ArrayList();
				for(int i = 0;i<dmlList.size();i++)
				{
					sqlsetList.clear();
					propertiesList.clear();
					sqlsetList = (List)dmlList.get(i);
					writeLog("***************************************dml action start***************************************");
					writeLog("获取数据值 sqlsetList : "+sqlsetList+" sqlsetList.size() : "+sqlsetList.size());
					if(null!=sqlsetList&&sqlsetList.size()>7)
					{
						String sqlsetid = (String)sqlsetList.get(0);
						String datasourceid = (String)sqlsetList.get(1);
						String dmltype = (String)sqlsetList.get(2);
						String dmlsql = (String)sqlsetList.get(3);
						String dmlfieldtypes = (String)sqlsetList.get(4);
						String dmlfieldnames = (String)sqlsetList.get(5);
						String dmlcuswhere = (String)sqlsetList.get(6);
						String dmlmainsqltype = (String)sqlsetList.get(7);
						String dmlcussql = (String)sqlsetList.get(8);
						String isresetright = (String)sqlsetList.get(9);
						String targetmodeid = (String)sqlsetList.get(10);
						int dmlsource = Util.getIntValue(Util.null2String(sqlsetList.get(11)),-1);
						String dmlsourcetype = (String)sqlsetList.get(12);
						try
						{
							if("detail".equals(dmlsourcetype)){
								String detailTable = getDetailTable( rs, dmlsource);   //获取明细表名称
								propertiesList = loadDetail(properties, request, detailTable);   //加载明细表数据
							}else {
								propertiesList.add(properties);  //主表数据
							}
							List<Property[]> NewpropertiesList = new ArrayList<Property[]>();
							if("detail".equals(dmlsourcetype)) {
								for (Property[] props : propertiesList) {
									int M=0;
									for(int n=0;n<props.length;n++){
										if(props[n].getName().equals("d.id")){
											M=n;
											break;
										}
									}
									writeLog("M="+M+"-明细id="+props[M].getValue()+"-待更新明细id="+detailid);
									if (props[M].getValue().equals("" + detailid)||this.isCardSubmit) {
										NewpropertiesList.add(props);
									}
								}
							}else{
								NewpropertiesList=propertiesList;
							}
							for(Property [] props : NewpropertiesList){

								fieldtypeList.clear();
								fieldnameList.clear();

								fieldnameList = Util.TokenizerString(dmlfieldnames, "|");
								fieldtypeList = Util.TokenizerString(dmlfieldtypes, "|");
								dmlcussql = (String)sqlsetList.get(8);
								dmlcuswhere = (String)sqlsetList.get(6);
								fieldvalueList.clear();
								//获取数据值
								this.getFieldValues(fieldname, props, dmlfieldtypes,dmlfieldnames,fieldtypeList, fieldnameList, fieldvalueList);

								writeLog("获取数据值 fieldtypeList : "+fieldtypeList+"    fieldnameList : "+fieldnameList+"   fieldvalueList : "+fieldvalueList);
								//替换自定dml sql的值
								dmlcussql = this.setDmlCusSqlOrWhereValues(fieldname, props,dmlcussql);
								dmlcuswhere = this.setDmlCusSqlOrWhereValues(fieldname, props,dmlcuswhere);
								DepartmentComInfo DepartmentComInfo1 = new DepartmentComInfo();
								SubCompanyComInfo subCompany = new SubCompanyComInfo();


								String userid = String.valueOf(user.getUID());//		当前操作者
								String userdepartmentid = String.valueOf(user.getUserDepartment());//		当前操作者部门
								String subDepIds = userdepartmentid;//		当前操作者部门（包含下级部门）
								subDepIds = getAllChildDeptByDepId(subDepIds);
								if(subDepIds.equals("")){
									subDepIds = userdepartmentid;
								}else{
									if(subDepIds.endsWith(",")){
										subDepIds = subDepIds.substring(0, subDepIds.length()-1);
									}
									subDepIds = userdepartmentid + "," + subDepIds;
								}
								String usersubcompanyid = String.valueOf(user.getUserSubCompany1());//		当前操作者分部
								String subSubIds = usersubcompanyid;//		当前操作者分部（包含下级分部）
								subSubIds = getAllChildSubBySubId(subSubIds);
								if(subSubIds.equals("")){
									subSubIds = usersubcompanyid;
								}else{
									if(subSubIds.endsWith(",")){
										subSubIds = subSubIds.substring(0, subSubIds.length()-1);
									}
									subSubIds = usersubcompanyid + "," + subSubIds;
								}
								String currentdate = TimeUtil.getCurrentDateString();//		当前日期
								String currenttime = (TimeUtil.getOnlyCurrentTimeString()).substring(0,5);//当前时间
								dmlsql = dmlsql.toLowerCase();
								dmlsql = dmlsql.replace("$userid$",userid);
								dmlsql = dmlsql.replace("$departmentid$",userdepartmentid);
								dmlsql = dmlsql.replace("$subcompanyid$",usersubcompanyid);
								dmlsql = dmlsql.replace("$date$",currentdate);
								dmlsql = dmlsql.replace("$time$",currenttime);
								dmlsql = dmlsql.replace("$alldepartmentid$",subDepIds);
								dmlsql = dmlsql.replace("$allsubcompanyid$",subSubIds);
								if(dmlsql.indexOf("$workcode$") != -1){
									String workcode = "";
									RecordSet recordSet = new RecordSet();
									recordSet.executeSql("SELECT workcode FROM hrmresource where id='"+user.getUID()+"'");
									if(recordSet.next()){
										workcode = Util.null2String(recordSet.getString("workcode"));
									}
									dmlsql = dmlsql.replace("$workcode$", workcode);
								}
								dmlcussql=replaceDynamicParm(dmlcussql, userid, userdepartmentid, usersubcompanyid, currentdate, currenttime, subDepIds, subSubIds);
								
								dmlcuswhere = dmlcuswhere.toLowerCase();
								dmlcuswhere = dmlcuswhere.replace("$userid$",userid);
								dmlcuswhere = dmlcuswhere.replace("$departmentid$",userdepartmentid);
								dmlcuswhere = dmlcuswhere.replace("$subcompanyid$",usersubcompanyid);
								dmlcuswhere = dmlcuswhere.replace("$date$",currentdate);
								dmlcuswhere = dmlcuswhere.replace("$time$",currenttime);
								dmlcuswhere = dmlcuswhere.replace("$alldepartmentid$",subDepIds);
								dmlcuswhere = dmlcuswhere.replace("$allsubcompanyid$",subSubIds);
								if(dmlcuswhere.indexOf("$workcode$") != -1){
									String workcode = "";
									RecordSet recordSet = new RecordSet();
									recordSet.executeSql("SELECT workcode FROM hrmresource where id='"+user.getUID()+"'");
									if(recordSet.next()){
										workcode = Util.null2String(recordSet.getString("workcode"));
									}
									dmlcuswhere = dmlcuswhere.replace("$workcode$", workcode);
								}


								//以sql的形式执行dmlaction
								// CHANGE START
								if (ShardingActionHelper.isModeSharding(Util.getIntValue(targetmodeid))) {
									// 如果是分表模块，将dml拆分执行，dmlsql+dmlcuswhere一组，dmlcussql一组，分表做分表检测和适配
									// 组一：dmlsql + dmlcuswhere
									if (!Strings.isNullOrEmpty(dmlsql)) {
										List<String> shardingDMLSqls = ShardingHelper.getShardingStatements(dmlsql);
										String originTable = extractTableName(dmlsql);
										for (String singleDMLSql : shardingDMLSqls) {
											String shardingTable = extractTableName(singleDMLSql);
											String suffix = shardingTable.replace(originTable, "");
											this.executeDMLAction(rst, rs,datasourceid,dmltype,singleDMLSql,fieldtypeList,fieldvalueList,dmlcuswhere.trim(),dmlmainsqltype,"",isresetright,targetmodeid, suffix);
											if (dmltype.equals("insert")) {
												break;
											}
										}
									}
									// 组二：dmlcussql
									if (!Strings.isNullOrEmpty(dmlcussql)) {
										List<String> shardingCustomSqls = ShardingHelper.getShardingStatements(dmlcussql);
										String originCustomTable = extractTableName(dmlcussql);
										for (String singleCustomSql : shardingCustomSqls) {
											String shardingTable = extractTableName(singleCustomSql);
											String suffix = shardingTable.replace(originCustomTable, "");
											this.executeDMLAction(rst, rs,datasourceid,dmltype,"",fieldtypeList,fieldvalueList,dmlcuswhere.trim(),dmlmainsqltype,singleCustomSql,isresetright,targetmodeid, suffix);
											if (dmltype.equals("insert")) {
												break;
											}
										}
									}
								} else {
									this.executeDMLAction(rst, rs,datasourceid,dmltype,dmlsql,fieldtypeList,fieldvalueList,dmlcuswhere.trim(),dmlmainsqltype,dmlcussql.trim(),isresetright,targetmodeid, "");
								}
								// CHAGNE END
							}
						}
						catch(Exception e)
						{
							writeLog("dmlaction e : "+e);
							dmlResult.put("flag", "false");
						}
					}
					writeLog("***************************************dml action end***************************************");
				}

			}
		}
		catch(Exception e)
		{
			writeLog("dml action执行出错 dmlaction e : "+e);
			dmlResult.put("flag", "false");
		}
		return this.SUCCESS;
	}

	/**
	 * 解析SQL语句中表名，目前支持update,insert,delete
	 * @param sql
	 * @return
	 */
	private String extractTableName(String sql) {
		String tablename = null;
		Pattern p = Pattern.compile(PATTERN_TABLE);
		Matcher matcher = p.matcher(sql);
		if (matcher.find()) {
			tablename = matcher.group(2);
		}
		return tablename;
	}

	/**
	 * 替换动态参数
	 * @param sql
	 * @param userid
	 * @param userdepartmentid
	 * @param usersubcompanyid
	 * @param currentdate
	 * @param currenttime
	 * @param subDepIds
	 * @param subSubIds
	 * @return
	 */
	private String replaceDynamicParm(String sql,String userid,String userdepartmentid,String usersubcompanyid,String currentdate
			,String currenttime,String subDepIds,String subSubIds){
		sql = sql.replaceAll("(?i)\\$userid\\$",userid);
		sql = sql.replaceAll("(?i)\\$departmentid\\$",userdepartmentid);
		sql = sql.replaceAll("(?i)\\$subcompanyid\\$",usersubcompanyid);
		sql = sql.replaceAll("(?i)\\$date\\$",currentdate);
		sql = sql.replaceAll("(?i)\\$time\\$",currenttime);
		sql = sql.replaceAll("(?i)\\$alldepartmentid\\$",subDepIds);
		sql = sql.replaceAll("(?i)\\$allsubcompanyid\\$",subSubIds);
		if(StringUtil.ignoreCaseIndexOf(sql, "workcode")>=0){
			String workcode = "";
			RecordSet recordSet = new RecordSet();
			recordSet.executeSql("SELECT workcode FROM hrmresource where id='"+user.getUID()+"'");
			if(recordSet.next()){
				workcode = Util.null2String(recordSet.getString("workcode"));
			}
			sql = sql.replaceAll("(?i)\\$workcode\\$", workcode);
		}
		return sql;
	}
	
	/**
	 * 获得所有下级部门ID
	 * @param depId
	 * @return
	 */
	public String getAllChildDeptByDepId(String depId){
		String str = "";
		try{
			if(depId.equals("0")){
				return str;
			}
			SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo();
			str = SubCompanyComInfo.getDepartmentTreeStr(depId);
		}catch(Exception e){
			writeLog(e);
		}
		return str;
	}

	/**
	 * 获得所有下级分部ID
	 * @param subId
	 * @return
	 */
	public String getAllChildSubBySubId(String subId){
		String str = "";
		try{
			if(subId.equals("0")){
				return str;
			}
			//SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo();
			str = SubCompanyComInfo.getSubCompanyTreeStr(subId);
		}catch(Exception e){
			writeLog(e);
		}
		return str;
	}

	private String getDetailTable(RecordSet rs,int tableid) throws Exception{
		String formDetailTable = "";
		String tsql = "select tablename from workflow_billdetailtable where id = " + tableid;
		rs.executeQuery(tsql);
		if(rs.next()){
			formDetailTable = Util.null2String(rs.getString("tablename"));
		}
		return formDetailTable;
	}

	/**
	 * 拼装明细表数据
	 * @param properties 主表数据
	 * @param requestInfo
	 * @param dtableName 明细表名称
	 * @return
	 */
	private List<Property[]> loadDetail(Property[] properties,RequestInfo requestInfo,String dtableName){
		List<Property[]> propertiesList = new ArrayList<Property[]>();
		DetailTable [] detailTables = requestInfo.getDetailTableInfo().getDetailTable();
		try{
			if(detailTables != null && detailTables.length > 0){
				for(DetailTable detailTable : detailTables){
					String tableName = Util.null2String(detailTable.getTableDBName());
					if(tableName != null && tableName.equalsIgnoreCase(dtableName)){  //取对应的明细表的数据
						int rowCount = detailTable.getRowCount();
						for(int i = 0 ;i < rowCount; i++){
							List<Property> propertyList = new ArrayList<Property>();
							for(Property property : properties){
								Property prop = new Property();
								BeanUtils.copyProperties(prop, property);
								propertyList.add(prop);
							}

							Row row = detailTable.getRow(i);

							Property tempprop = new Property();
							tempprop.setName("d.id");
							tempprop.setValue(row.getId());
							tempprop.setType("");
							propertyList.add(tempprop);

							Cell [] cells = row.getCell();
							for(Cell cell : cells){
								String name = Util.null2String(cell.getName());
								String value = Util.null2String(cell.getValue());
								String type = Util.null2String(cell.getType());
								if(!"".equals(name)){
									name = "d." + name;
									Property prop = new Property();
									prop.setName(name);
									prop.setValue(value);
									prop.setType(type);
									propertyList.add(prop);
								}
							}

							Property [] props = propertyList.toArray(new Property[1]);
							propertiesList.add(props);
						}
					}
				}
			}
		}catch (Exception e) {
			writeLog("加载明细表数据出错:" + e);
		}
		return propertiesList;
	}

	/**
	 * 添加固定值
	 * @param properties
	 * @param request
	 * @return
	 */
	private Property[] addSpecialFieldValue(Property[] properties,RequestInfo request){
		String id = request.getRequestid();
		String formmodeid = request.getWorkflowid();
//		writeLog("formmodeid:"+formmodeid+"	id:"+id);
//		writeLog("properties.length:"+properties.length);
		int plength = properties.length;
		properties = (Property[]) expand(properties,plength+3);

		Property Property = new Property();
		Property.setName("formmodeid");
		Property.setValue(String.valueOf(formmodeid));
		properties[plength] = Property;

		Property = new Property();
		Property.setName("id");
		Property.setValue(String.valueOf(id));
		properties[plength+1] = Property;

//		Property = new Property();
//		Property.setName("requestid");
//		Property.setValue(String.valueOf(id));
//		properties[plength+2] = Property;
		Property = new Property();
		Property.setName("form_biz_id");
		Property.setValue(String.valueOf(request.getRequestid()));
		properties[plength+2] = Property;

		return properties;
	}

	/**
	 * 获取dmlaction 属性
	 * @param rst
	 * @param rs
	 * @return
	 * @throws Exception
	 */
	private List getDmlActionSet(RecordSetTrans rst,RecordSet rs) throws Exception
	{
		List dmlList = new ArrayList();
		StringBuffer sqlsb = new StringBuffer();
		sqlsb.append("select t.id,");
		sqlsb.append("s.datasourceid,");
		sqlsb.append("s.dmltype,");
		sqlsb.append("s.isresetright,");
		sqlsb.append("s.targetmodeid,");
		sqlsb.append("t.dmlsql,");
		sqlsb.append("t.dmlfieldtypes,");
		sqlsb.append("t.dmlfieldnames,");
		sqlsb.append("t.dmlcuswhere,");
		sqlsb.append("t.dmlmainsqltype,");
		sqlsb.append("t.dmlcussql,");
		sqlsb.append("s.dmlsource,");
		sqlsb.append("s.dmlsourcetype");
		sqlsb.append(" from mode_dmlactionset s, mode_dmlactionsqlset t");
		sqlsb.append(" where s.id = t.actionid");
		sqlsb.append(" and s.expandid ="+expandid);

		if(actionid > 0){
			sqlsb.append(" and s.id="+actionid);
		}
		sqlsb.append("	 order by s.dmlorder");
		writeLog("获取dmlaction 属性 sqlsb : "+sqlsb.toString());
		if(null!=rst)
		{
			rst.executeSql(sqlsb.toString());
			while(rst.next())
			{
				List sqlsetList = this.setSqlsetList(rst, null);
				if(sqlsetList.size()>0)
				{
					dmlList.add(sqlsetList);
				}
			}
		}
		else if(null!=rs)
		{
			rs.executeSql(sqlsb.toString());
			while(rs.next())
			{
				List sqlsetList = this.setSqlsetList(null, rs);
				if(sqlsetList.size()>0)
				{
					dmlList.add(sqlsetList);
				}
			}
		}
		return dmlList;
	}
	/**
	 * 将dmlaction属性进行组装
	 * @param rst
	 * @param rs
	 * @return
	 */
	private List setSqlsetList(RecordSetTrans rst,RecordSet rs)
	{
		List sqlsetList = new ArrayList();
		if(null!=rst)
		{
			sqlsetList.add(rst.getString("id"));
			sqlsetList.add(rst.getString("datasourceid"));
			sqlsetList.add(rst.getString("dmltype"));
			sqlsetList.add(rst.getString("dmlsql"));
			sqlsetList.add(rst.getString("dmlfieldtypes"));
			sqlsetList.add(rst.getString("dmlfieldnames"));
			sqlsetList.add(rst.getString("dmlcuswhere"));
			sqlsetList.add(rst.getString("dmlmainsqltype"));
			sqlsetList.add(rst.getString("dmlcussql"));
			sqlsetList.add(rst.getString("isresetright"));
			sqlsetList.add(rst.getString("targetmodeid"));
			sqlsetList.add(rst.getString("dmlsource"));
			sqlsetList.add(rst.getString("dmlsourcetype"));
		}
		else if(null!=rs)
		{
			sqlsetList.add(rs.getString("id"));
			sqlsetList.add(rs.getString("datasourceid"));
			sqlsetList.add(rs.getString("dmltype"));
			sqlsetList.add(rs.getString("dmlsql"));
			sqlsetList.add(rs.getString("dmlfieldtypes"));
			sqlsetList.add(rs.getString("dmlfieldnames"));
			sqlsetList.add(rs.getString("dmlcuswhere"));
			sqlsetList.add(rs.getString("dmlmainsqltype"));
			sqlsetList.add(rs.getString("dmlcussql"));
			sqlsetList.add(rs.getString("isresetright"));
			sqlsetList.add(rs.getString("targetmodeid"));
			sqlsetList.add(rs.getString("dmlsource"));
			sqlsetList.add(rs.getString("dmlsourcetype"));
		}
		return sqlsetList;
	}
	/**
	 * 获取数据值
	 * @param rst
	 * @param rs
	 * @param fieldname
	 * @param properties
	 * @param sqlsetList
	 * @param fieldtypeList
	 * @param fieldnameList
	 * @param fieldvalueList
	 */
	private void getFieldValues(String fieldname,Property[] properties,String dmlfieldtypes,String dmlfieldnames,List fieldtypeList,List fieldnameList,List fieldvalueList)
	{
		//填充空数据
		for(int i = 0;i<fieldnameList.size();i++)
		{
			fieldvalueList.add("");
		}
		//获取各字段值
		for (int j = 0; j < properties.length; j++)
		{
			// 主表数据
			String name = properties[j].getName().toLowerCase();
			String value = Util.null2String(properties[j].getValue());
			String type = Util.null2String(properties[j].getType());
			if(type.equalsIgnoreCase("int")||type.equalsIgnoreCase("int(11)")||type.startsWith("decimal")){
				if(value.equals("")){
					value = null;
				}
			}
			for(int f = 0;f<fieldnameList.size();f++)
			{
				fieldname = "";
				fieldname = (String)fieldnameList.get(f);
				fieldname = fieldname.toLowerCase();
				if(fieldname.indexOf("=")>0){
					String[] arr = fieldname.split("=");
					if(arr.length==2){
						fieldname = arr[1];
					}
				}
				if (name.compareTo(fieldname)==0)
				{
					fieldvalueList.set(f, value);
					//break;这里不能使用break，因为同一个字段，可能被设置多次
				}
			}
		}
		writeLog("字段数量与字段值数量 fieldvalueList : "+fieldvalueList+"  fieldnameList : "+fieldnameList);
		//字段数量与字段值数量不一致
		if(fieldvalueList.size()<=0||(fieldvalueList.size()!=fieldnameList.size()))
		{
			writeLog("字段数量与字段值数量不一致!");
			fieldnameList.clear();
			fieldtypeList.clear();
			fieldvalueList.clear();
		}
	}

	/**
	 * 替换自定义条件sql的值
	 * @param fieldname
	 * @param properties
	 * @param dmlcuswhere
	 * @return
	 */
	private String setDmlCusSqlOrWhereValues(String fieldname,Property[] properties,String dmlsql)
	{
		//获取各字段值
		for (int j = 0; j < properties.length; j++)
		{
			// 主表数据
			String name = properties[j].getName().toLowerCase();
			String value = Util.null2String(properties[j].getValue());
			String type = Util.null2String(properties[j].getType());
			if(type.equalsIgnoreCase("int")||type.equalsIgnoreCase("int(11)") || type.startsWith("decimal")){
				if(value.equals("")){
					value = null;
				}
			}
			if(value==null){
				dmlsql = dmlsql.replaceAll("'(?i)\\{\\?"+name+"\\}'","null");
				dmlsql = dmlsql.replaceAll("(?i)\\{\\?"+name+"\\}","null");
			}else{
				//把值中的单引号替换成两个单引号
				value = value.replace("'","''");
				dmlsql = dmlsql.replaceAll("(?i)\\{\\?"+name+"\\}",Matcher.quoteReplacement(value));
			}
		}
		return dmlsql;
	}
	/**
	 * 以sql的形式执行dmlaction
	 * @param rst
	 * @param rs
	 * @param datasourceid
	 * @param dmltype
	 * @param dmlsql
	 * @param fieldtypeList
	 * @param fieldvalueList
	 * @param dmlcuswhere
	 * @param dmlcussql
	 */
	private void executeDMLAction(RecordSetTrans rst,RecordSet rs,String datasourceid,String dmltype,String dmlsql,List fieldtypeList,List fieldvalueList,String dmlcuswhere,String dmlmainsqltype,String dmlcussql,String isresetright,String targetmodeid, String suffix )
	{
		ModeRightInfo modeRightInfo = new ModeRightInfo();
		// CHANGE START
		modeRightInfo.setSuffix(suffix);
		// CHANGE END
		ConnStatementDataSource connStatementDataSource = null;
		ConnStatement connStatement = null;
		List<String> sqlList = new ArrayList<String>();
		List<String> insertSqlList = new ArrayList<String>();
		List<String> rightList = new ArrayList<String>();
		List<String> topList = new ArrayList<String>();
		List<String> seclevelList = new ArrayList<String>();
		List<String> topSqlList = new ArrayList<String>();
		List<String> seclevelSqlList = new ArrayList<String>();

		Map<String,Object> updateDataMap = new HashMap<String, Object>();
		List<Integer> ids = new ArrayList<Integer>();
		String selectUpdateSql="";//insert into select 这种形式的sql插入后,更新模块id等字段
		try
		{
			String dbtype = DBTypeUtil.getDataSourceDbtype(rs,datasourceid);

			if("".equals(datasourceid))
			{
				connStatement = new ConnStatement();
			}
			else
			{
				connStatementDataSource = new ConnStatementDataSource(datasourceid);
			}
			writeLog("以sql的形式执行dmlaction dmltype : "+dmltype+" dmlsql : "+dmlsql+" dmlcuswhere : "+dmlcuswhere+"  dmlmainsqltype : "+dmlmainsqltype+"  dmlcussql : "+dmlcussql+" fieldvalueList : "+fieldvalueList.size());
			//如果为update或者delete，必须有条件
			if(dmltype.equals("update")||dmltype.equals("delete"))
			{

					//先执行设置的sql
					if(!"".equals(dmlsql)&&(dmlsql.toLowerCase().indexOf(" where ")>-1||!"".equals(dmlcuswhere)))
					{

						if(!"".equals(dmlcuswhere))
						{
							if(dmlsql.toLowerCase().indexOf(" where ")>-1)
							{
								dmlsql += " and "+dmlcuswhere;
							}
							else
							{
								dmlsql += " where "+dmlcuswhere;
							}
						}
						//update操作后执行更新权限
						if("".equals(datasourceid)&&dmltype.equals("update")) {
							if(isresetright.equals("1")) {  //开启需权限重构
								String querySql = getQuerySql(dmltype, dmlsql, fieldtypeList);
								if (!querySql.equals("")) {
									connStatement.setStatementSql(querySql);
									writeLog("--tag1--dmltype--" + dmltype + ",设置字段update语句dmlsql：" + dmlsql + "，权限查询querySql：" + querySql);
									Pattern p = Pattern.compile("\\?", Pattern.CASE_INSENSITIVE);
									Matcher m = p.matcher(querySql);
									int count = 0;
									while (m.find()) {
										count++;
									}
									if (count > 0) {
										int start = fieldtypeList.size() - count;
										List fieldtypeListTemp = fieldtypeList.subList(start, fieldtypeList.size());
										List fieldvalueListTemp = fieldvalueList.subList(start, fieldtypeList.size());
										for (int i = 0; i < fieldtypeListTemp.size(); i++) {
											String fielddbtype = (String) fieldtypeListTemp.get(i);
											String fieldvalue = (String) fieldvalueListTemp.get(i);
											boolean ischeck = DBTypeUtil.checkFieldDBType(fielddbtype, dbtype);
											String settype = DBTypeUtil.getThistype();
											this.setValueWithDBTypeInStatment(i + 1, connStatementDataSource, connStatement, settype, fieldvalue);
										}
									}
									RecordSet rs1 = new RecordSet();
									connStatement.executeQuery();
									String maintablename = "";
									List<Integer> updateids = new ArrayList<Integer>();
									while (connStatement.next()) {
										int id = connStatement.getInt("id");
										int formmodeid = 0;
										int modedatacreater = 0;
										String tablename = querySql.substring(querySql.indexOf("from") + 4, querySql.indexOf("where")).trim();
										String tempTablename = tablename.replaceAll("_dt\\d+", "");
										maintablename = tempTablename;
										if (!tablename.equals(tempTablename)) { //如果是明细表,则权限计算时以主表为准
											String sql = "select d1.mainid,t.formmodeid,t.modedatacreater from " + tempTablename + " t left join " + tablename + " d1 on t.id=d1.mainid where d1.id= " + id;
											rs1.executeQuery(sql);
											if (rs1.next()) {
												id = Util.getIntValue(Util.null2String(rs1.getString("mainid")));
											}
											formmodeid = rs1.getInt("formmodeid");
											modedatacreater = rs1.getInt("modedatacreater");
										} else {
											formmodeid = connStatement.getInt("formmodeid");
											modedatacreater = connStatement.getInt("modedatacreater");
										}

										if (formmodeid > 0) {
											updateids.add(id);
										}
										if (formmodeid > 0 && modedatacreater > 0) {
											String val = modedatacreater + "_" + formmodeid + "_" + id;
											if (!topList.contains(val)) {
												topList.add(val);
											}
										}
									}

									rightList = topList;
									ids = updateids;
									updateDataMap.put("tablename", maintablename);
									updateDataMap.put("updateids", updateids);
								}
							}
						}
						//获取更新数据的表单id 表单名称    res 已经不使用，存储过程执行getQuerySql会导致报错不执行
						//Map<String,Object> res = getUpdateDatas(ids,rs,dmltype,dmlsql,fieldtypeList,datasourceid);
						//更新数据放在最后,否则若条件字段也参与了被赋值字段,会导致上面的更新权限找不到记录
						this.executesql(dbtype,connStatementDataSource, connStatement, dmlsql, fieldtypeList, fieldvalueList);
					}

				//再执行自定义dmlsql
				if((dmlcussql.toLowerCase().indexOf("where")>-1&&Util.getIntValue(dmlmainsqltype, 0)==0)||(!dmlcussql.equals("")&&Util.getIntValue(dmlmainsqltype, 0)==1))
				{
						//执行完自定义dml后，执行更新权限
						if(isresetright.equals("1")&&dmlcussql.toLowerCase().indexOf("update")!=-1&&dmlcussql.toLowerCase().indexOf("where")!=-1){
							String lowserDmlcussql = dmlcussql.toLowerCase();
							String tablename = lowserDmlcussql.substring(lowserDmlcussql.indexOf("update")+6,lowserDmlcussql.indexOf("set")).trim();
							String tempTablename=tablename.replaceAll("_dt\\d+", "");
							String sqlwhere = "";
							if(!dmlcussql.contains("insert")){
								sqlwhere = dmlcussql.substring(lowserDmlcussql.lastIndexOf("where"));
							}
							String querySql = "select * from "+tablename+" "+sqlwhere;
							writeLog("--tag2--dmltype--"+dmltype+",自定义update语句dmlcussql："+dmlcussql);
							writeLog("权限查询querySql："+querySql);
//							rs.executeQuery(querySql);
							connStatement.setStatementSql(querySql);
							Pattern p = Pattern.compile("\\?",Pattern.CASE_INSENSITIVE);
							Matcher m = p.matcher(querySql);
							int count = 0;
							while(m.find()){
								count ++;
							}
							try {
//								if (count>0&&count<=dmlcussqlvalue.size()) {
//									int sqlvlasize=dmlcussqlvalue.size();
//									int start=sqlvlasize-count;
//									for (int i = 0; i < count; i++) {
//										String value = Util.null2String(dmlcussqlvalue.get(start+i));
//										this.setValueWithDBTypeInStatment(i+1, connStatementDataSource, connStatement, "1", ""+value);
//									}
//								}
							connStatement.executeQuery();
							int id=0;
							int formmodeid = 0;
							int modedatacreater = 0;
							RecordSet rs1 = new RecordSet();
							String maintablename = tempTablename;
							List<Integer> updateids = new ArrayList<Integer>();
							while (connStatement.next()) {
								id=Util.getIntValue(Util.null2String(connStatement.getString("id")));
								if (!tablename.equals(tempTablename)) {//如果是明细表,则权限计算时以主表为准
									String sql="select d1.mainid,t.formmodeid,t.modedatacreater from "+tempTablename +" t left join "+tablename+" d1 on t.id=d1.mainid where d1.id= "+id;
									rs1.executeQuery(sql);
									if (rs1.next()) {
										id=Util.getIntValue(Util.null2String(rs1.getString("mainid")));
									}
									formmodeid = rs1.getInt("formmodeid");
									modedatacreater = rs1.getInt("modedatacreater");
								}else {
									formmodeid = connStatement.getInt("formmodeid");
									modedatacreater = connStatement.getInt("modedatacreater");
								}
								if(formmodeid>0){
									updateids.add(id);
								}
								if(formmodeid>0&&modedatacreater>0){
									String val = modedatacreater+"_"+formmodeid+"_"+id;
									if(!rightList.contains(val)){
										rightList.add(val);
										topList.add(val);
									}
								}
							}
							ids = updateids;
							writeLog("记录到的需权限重构的数据id："+rightList);
							updateDataMap.put("tablename", maintablename);
							updateDataMap.put("updateids", updateids);
							} catch (Exception e) {
								writeLog("查询权限重构出错..."+querySql);
						}

						}else if (dmlcussql.toLowerCase().indexOf("update")!=-1&&dmlcussql.toLowerCase().indexOf("where")!=-1&&"".equals(datasourceid)){//处理置顶的数据

							String lowserDmlcussql = dmlcussql.toLowerCase();
							String tablename = lowserDmlcussql.substring(lowserDmlcussql.indexOf("update")+6,lowserDmlcussql.indexOf("set")).trim();
							String tempTablename=tablename.replaceAll("_dt\\d+", "");
							String sqlwhere = "";
							if(!dmlcussql.contains("insert")){
								sqlwhere = dmlcussql.substring(lowserDmlcussql.lastIndexOf("where"));
							}
							String querySql = "select * from "+tablename+" "+sqlwhere;
							try {
								connStatement.setStatementSql(querySql);
								Pattern p = Pattern.compile("\\?",Pattern.CASE_INSENSITIVE);
								Matcher m = p.matcher(querySql);
								int count = 0;
								while(m.find()){
									count ++;
								}

								connStatement.executeQuery();
								int id=0;
								int formmodeid = 0;
								int modedatacreater = 0;
								RecordSet rs1 = new RecordSet();
								String maintablename = tempTablename;
								List<Integer> updateids = new ArrayList<Integer>();
								while (connStatement.next()) {
									id=Util.getIntValue(Util.null2String(connStatement.getString("id")));
									if (!tablename.equals(tempTablename)) {//如果是明细表,则权限计算时以主表为准
										String sql="select d1.mainid,t.formmodeid,t.modedatacreater from "+tempTablename +" t left join "+tablename+" d1 on t.id=d1.mainid where d1.id= "+id;
										rs1.executeQuery(sql);
										if (rs1.next()) {
											id=Util.getIntValue(Util.null2String(rs1.getString("mainid")));
										}
										formmodeid = rs1.getInt("formmodeid");
										modedatacreater = rs1.getInt("modedatacreater");
									}else {
										formmodeid = connStatement.getInt("formmodeid");
										modedatacreater = connStatement.getInt("modedatacreater");
									}
									if(formmodeid>0){
										updateids.add(id);
									}
									if(formmodeid>0&&modedatacreater>0){
										String val = modedatacreater+"_"+formmodeid+"_"+id;
										if(!topList.contains(val)){
											topList.add(val);
										}
									}
								}
							} catch (Exception e) {
								writeLog("置顶计算出错..."+querySql);
							}

						}

						//获取更新数据的表单id 表单名称  res 已经不使用，存储过程执行getQuerySql会导致报错不执行
						//Map<String,Object> res = getUpdateDatas(ids,rs,dmltype,dmlcussql,fieldtypeList,datasourceid);
						//更新数据放在最后,否则若条件字段也参与了被赋值字段,会导致上面的更新权限找不到记录
						this.executesql(dbtype,connStatementDataSource, connStatement, dmlcussql, null, null);
				}
			}
			else
			{
				if(fieldvalueList.size()>0&&!"".equals(dmlsql))
				{
					this.executesql(dbtype,connStatementDataSource, connStatement, dmlsql, fieldtypeList, fieldvalueList);
					//insert操作后执行更新权限
					if(Util.getIntValue(targetmodeid,-1)>0&&"".equals(datasourceid)){
						String querySql = getQuerySql(dmltype, dmlsql,fieldvalueList);
						if(!querySql.equals("")){
							connStatement.setStatementSql(querySql);
							writeLog("--tag3--dmltype--"+dmltype+",设置字段update语句dmlsql："+dmlsql+"，权限查询querySql："+querySql);
							Pattern p = Pattern.compile("\\?",Pattern.CASE_INSENSITIVE);
							Matcher m = p.matcher(querySql);
							int count = 0;
							while(m.find()){
								count ++;
							}
							if(count>0){
								int start = fieldtypeList.size()-count;
								List fieldtypeListTemp =  fieldtypeList.subList(start, fieldtypeList.size());
								List fieldvalueListTemp =  fieldvalueList.subList(start, fieldtypeList.size());
								for(int i = 0;i<fieldtypeListTemp.size();i++){
									String fieldvalue = (String)fieldvalueListTemp.get(i);
									String settype = DBTypeUtil.getThistype();
									this.setValueWithDBTypeInStatment(i+1, connStatementDataSource, connStatement, settype, fieldvalue);
								}
							}
							connStatement.executeQuery();
							if(connStatement.next()){
								String id = connStatement.getString("id");
								String tablename="";
								if(querySql.contains("where")){
									 tablename = querySql.substring(querySql.indexOf("from")+4,querySql.indexOf("where")).trim();
								}else {
									 tablename = querySql.substring(querySql.indexOf("from")+4).trim();
								}
								String sql = "select b.tablename from WORKFLOW_BILLFIELD bill left join modeinfo info on info.formid=bill.billid left join WORKFLOW_BILL b on b.id=bill.billid where info.id=? and bill.DETAILTABLE=? ";
								RecordSet rs1 = new RecordSet();
								boolean isdetail=false;//是否插入明细表
								// CHANGE START
								rs1.executeQuery(sql, targetmodeid,tablename.replace(suffix, ""));
								// CHAGNE END
								String tempTablename=tablename;
								if (rs1.next()) {
									tablename=Util.null2String(rs1.getString("tablename"));//如果是明细表,则权限计算时以主表为准
									isdetail=true;
								}
								if(dbtype.equals("oracle")){
									sql = " select 1 from user_tab_columns where upper(table_name)=upper('"+tablename+"') and upper(COLUMN_NAME) = upper('formmodeid')";
								}else if(dbtype.equals("mysql")){
									String dbname = CommonConstant.DB_MYSQL_SCHEMA;
									sql = " select 1 from information_schema.COLUMNS where upper(TABLE_SCHEMA)=upper('"+dbname+"') and upper(table_name)=upper('"+tablename+"')  and upper(COLUMN_NAME) = upper('formmodeid')";
								}
								else if(dbtype.equals("postgresql")){
                            		sql = " select 1 from information_schema.COLUMNS where lower(TABLE_SCHEMA)=lower('public') and lower(table_name)=lower('"+tablename+"')  and lower(COLUMN_NAME) = lower('formmodeid')";
								}
								else {
									sql = " select 1 from sysobjects o,syscolumns c where o.id=c.id and upper(o.name)=upper('"+tablename+"') and upper(c.name) = upper('formmodeid')";
								}
								rs1.executeSql(sql);
								if(rs1.next()){
									String date = DateHelper.getCurrentDate();
									String time = DateHelper.getCurrentTime();
									if(creator<=0){
										creator = 1;
									}
									if (isdetail&&!tablename.equals(tempTablename)) {
										sql="select mainid from "+tempTablename+" where id= "+id;
										rs1.executeQuery(sql);
										if (rs1.next()) {
											id=Util.null2String(rs1.getString("mainid"));
										}
									}
									// TODO formbizid生成、modeuuid生成
									// CHANGE START
//									String sql;
									String formBizId;
									String modeuuid = UUID.randomUUID().toString();
									if (ShardingActionHelper.isModeSharding(Util.getIntValue(targetmodeid))) {
										int shardingFormId = ShardingActionHelper.getShardingFormId(modeid, suffix);
										formBizId = ShardingActionHelper.constructBizId(Integer.parseInt(id), shardingFormId, true);
									} else {
										String formId = ShardingActionHelper.getFormId(Integer.parseInt(targetmodeid));
										formBizId = ShardingActionHelper.constructBizId(Integer.parseInt(id), Integer.parseInt(formId));
									}
									if (ShardingActionHelper.checkBizIdExists(tempTablename)) {
										sql = "update "+tempTablename+" set formmodeid="+targetmodeid+",modedatacreater="+creator+",modedatacreatertype=0,modedatacreatedate='"+date+"',modedatacreatetime='"+time+"', "+ ShardingHelper.KEY_FORM_BIZ_ID + "='" + formBizId + "', MODEUUID='"+modeuuid +"' where id="+id;
									} else {
										sql = "update "+tempTablename+" set formmodeid="+targetmodeid+",modedatacreater="+creator+",modedatacreatertype=0,modedatacreatedate='"+date+"',modedatacreatetime='"+time+"',  MODEUUID='"+modeuuid+"' where id="+id;
									}
									// CHAGNE END
//									sql = "update "+tablename+" set formmodeid="+targetmodeid+",modedatacreater="+creator+",modedatacreatertype=0,modedatacreatedate='"+date+"',modedatacreatetime='"+time+"' where id="+id;
									rs1.executeSql(sql);
									String val = creator+"_"+targetmodeid+"_"+id;
									if(isresetright.equals("1")&&!rightList.contains(val)){
										rightList.add(val);
									}
									if(!topList.contains(val)){
										topList.add(val);
									}
									if(!seclevelList.contains(val)){
										seclevelList.add(val);
									}

								}
							}
						}
					}
				}
				//再执行自定义dmlsql
				if(!"".equals(dmlcussql)){
						String lowserDmlcussql = dmlcussql.toLowerCase();
					if(Util.getIntValue(dmlmainsqltype, 0)==0 && lowserDmlcussql.indexOf("insert")!=-1&&lowserDmlcussql.indexOf("select")!=-1//insert into ... select这种形式的
							&&!StringHelper.isEmpty(targetmodeid)&&!"0".equals(targetmodeid)){
						String tablename = getTableName(lowserDmlcussql);
						boolean isdetail = tablename.indexOf("_dt")>=0;
						tablename=tablename.replaceAll("_dt\\d+", "");
						DatabaseUtils dbUtils = new DatabaseUtils();
						if(tablename.startsWith("uf_")&&dbUtils.existsColumn(tablename, "modeuuid") && !isdetail){//不是建模表单跳过
							try {
								int selectIndex=lowserDmlcussql.indexOf("select");
								String insertsql=lowserDmlcussql.substring(0, selectIndex);
								String selectsql=lowserDmlcussql.substring(selectIndex);
								insertsql=insertsql.substring(0,insertsql.lastIndexOf(")"));
								insertsql+=" ,modeuuid)";
								String modeuuid= UUID.randomUUID().toString();
								selectsql=selectsql.substring(0,selectsql.indexOf("from"))+" ,'"+modeuuid+"' "+selectsql.substring(selectsql.indexOf("from"));
								dmlcussql=insertsql+selectsql;
                                if(isresetright.equals("1")) {
                                    sqlList.add("select * from " + tablename + " where modeuuid='" + modeuuid + "'");
                                }
								topSqlList.add("select * from " + tablename + " where modeuuid='" + modeuuid + "'");
								seclevelSqlList.add("select * from " + tablename + " where modeuuid='" + modeuuid + "'");
								selectUpdateSql= "update "+tablename+" set formmodeid="+targetmodeid+",modedatacreater="+creator+",modedatacreatertype=0,modedatacreatedate='"+DateHelper.getCurrentDate()+"',modedatacreatetime='"+DateHelper.getCurrentTime()+"' where modeuuid='"+modeuuid+"'";
								writeLog("dmlcussql:"+dmlcussql);
							} catch (Exception e) {
								writeLog(e);
							}
						}
					}
					
					//第三方库存储过程使用executeProc2方法
					if(!"".equals(datasourceid)&& (dmlcussql.startsWith("call") || dmlcussql.startsWith("EXECUTE") || dmlcussql.startsWith("execute")) ){

							RecordSet recordSet1=new RecordSet();
							int  index = dmlcussql.indexOf(" ");
							String proString = dmlcussql.substring(index,dmlcussql.length());
							int index2= proString.trim().indexOf(" ");
							String proName =proString.substring(0,index2+1);
							String parms = proString.substring(index2+1,proString.length()).replace("(","").replace(")","");
							char flag = new Util().getSeparator();
							String parm = parms.trim().replaceAll(",",flag+"").replaceAll("'","");
							try {
								recordSet1.executeProc2(proName,parm,datasourceid);
							}catch (Exception e) {
								writeLog("执行sql出错 e : ");
								writeLog(e);
								dmlResult.put("flag", "false");
							}
					}else {
						this.executesql(dbtype,connStatementDataSource, connStatement, dmlcussql, null, null);
					}
					//执行完自定义dml后，执行更新权限
					if(lowserDmlcussql.indexOf("insert")!=-1&&lowserDmlcussql.indexOf("values")!=-1
							&&!StringHelper.isEmpty(targetmodeid)&&!"0".equals(targetmodeid)
							&& dmlResult.containsKey("flag") && !dmlResult.get("flag").equals("false")){
						String querySql = getQuerySql(dmltype, dmlcussql,fieldvalueList);
						if(!querySql.equals("")){
							connStatement.setStatementSql(querySql);
							writeLog("--tag4--dmltype--"+dmltype+",设置字段update语句dmlsql："+dmlsql+"，权限查询querySql："+querySql);
							connStatement.executeQuery();
							if(connStatement.next()){
								String id = connStatement.getString("id");
								String tablename=getTableName(dmlcussql);
								String tempTablename=tablename.replaceAll("_dt\\d+", "");
								boolean isdetail=!tempTablename.equals(tablename);
								String date = DateHelper.getCurrentDate();
								String time = DateHelper.getCurrentTime();
								if(creator<=0){
									creator = 1;
								}
								RecordSet recordSet = new RecordSet();
								if (isdetail) {
									String sql="select mainid from "+tablename+" where id= "+id;
									//connStatement.setStatementSql(sql);
                                    recordSet.executeQuery(sql);
                                    if (recordSet.next()) {
										id=Util.null2String(recordSet.getString("mainid"));
									}
								}
								// CHANGE START
								String sql;
								String formBizId;
								String modeuuid = UUID.randomUUID().toString();
								if (ShardingActionHelper.isModeSharding(Util.getIntValue(targetmodeid))) {
									int shardingFormId = ShardingActionHelper.getShardingFormId(modeid, suffix);
									formBizId = ShardingActionHelper.constructBizId(Integer.parseInt(id), shardingFormId, true);
								} else {
									String formId = ShardingActionHelper.getFormId(Integer.parseInt(targetmodeid));
									formBizId = ShardingActionHelper.constructBizId(Integer.parseInt(id), Integer.parseInt(formId));
								}
								if (ShardingActionHelper.checkBizIdExists(tempTablename)) {
									sql = "update "+tempTablename+" set formmodeid="+targetmodeid+",modedatacreater="+creator+",modedatacreatertype=0,modedatacreatedate='"+date+"',modedatacreatetime='"+time+"', "+ ShardingHelper.KEY_FORM_BIZ_ID + "='" + formBizId + "', MODEUUID='"+modeuuid +"' where id="+id;
								} else {
									sql = "update "+tempTablename+" set formmodeid="+targetmodeid+",modedatacreater="+creator+",modedatacreatertype=0,modedatacreatedate='"+date+"',modedatacreatetime='"+time+"',  MODEUUID='"+modeuuid+"' where id="+id;
								}
								// CHAGNE END
								//connStatement.setStatementSql(sql);
								//connStatement.executeUpdate();
                                recordSet.executeUpdate(sql);
                                String val = creator+"_"+targetmodeid+"_"+id;
								if(isresetright.equals("1")&&!rightList.contains(val)){
									rightList.add(val);
								}


								if(!topList.contains(val)){
									topList.add(val);
								}
								if(!seclevelList.contains(val)){
									seclevelList.add(val);
								}

							}
						}
					}else if(isresetright.equals("1")&&dmlcussql.toLowerCase().indexOf("update")!=-1&&dmlcussql.toLowerCase().indexOf("where")!=-1){
						String tablename = lowserDmlcussql.substring(lowserDmlcussql.indexOf("update")+6,lowserDmlcussql.indexOf("set")).trim();
						String sqlwhere = dmlcussql.substring(lowserDmlcussql.indexOf("where"));
						String querySql = "select * from "+tablename+" "+sqlwhere;
						writeLog("--tag5--dmltype--"+dmltype+",设置字段update语句dmlcussql："+dmlcussql+"，权限查询querySql："+querySql);
						sqlList.add(querySql);
						topSqlList.add(querySql);
					}

				}
			}
		}
		catch(Exception e)
		{
			dmlResult.put("flag", "false");
			writeLog("执行sql出错 e : ");
			writeLog(e);
		}
		finally
		{
			try
			{
				if(null!=connStatementDataSource)
				{
					connStatementDataSource.close();
					connStatementDataSource = null;
				}
				if(null!=connStatement)
				{
					connStatement.close();
					connStatement = null;
				}

                RecordSet rs1 = new RecordSet();

                for(int i=0;i<insertSqlList.size();i+=2){
					int idtemp = -1;
                    String querySql = insertSqlList.get(i);
					if(!StringHelper.isEmpty(querySql) && querySql.startsWith("select")){
						rs1.executeSql(querySql);
						while(rs1.next()){
							idtemp = rs1.getInt("id");
							try {
								String tablename=querySql.substring(querySql.indexOf("from")+4, querySql.indexOf("where"));
								if(isresetright.equals("1")){
									sqlList.add("select * from "+tablename+" where id="+idtemp);
						}

								topSqlList.add("select * from "+tablename+" where id="+idtemp);
								seclevelSqlList.add("select * from "+tablename+" where id="+idtemp);
							} catch (Exception e) {
								writeLog(e);
					}
						}
					}
					querySql = insertSqlList.get(i+1);
                    if(!StringHelper.isEmpty(querySql) && querySql.startsWith("update")){
                        rs1.executeUpdate(querySql, idtemp);
                    }
                }

                if(!"".equals(selectUpdateSql)){
                	rs1.executeUpdate(selectUpdateSql);
                }

				//由于connStatement在oracle中出现update操作在close之后才真正提交值的情况，把权限重构放在close之后
				Map<String,String> paramsForTop = new HashMap<>();
				ModeComInfo modeComInfo = new ModeComInfo();
				//获取表单名称
				WorkflowBillComInfo workflowBillComInfo = new WorkflowBillComInfo();

				for(int i=0;i<sqlList.size();i++){
					String querySql = sqlList.get(i);
					rs1.executeSql(querySql);
					while(rs1.next()){
						int id = rs1.getInt("id");
						int formmodeid = rs1.getInt("formmodeid");
						int modedatacreater = rs1.getInt("modedatacreater");
						if(formmodeid>0&&modedatacreater>0){
							modeRightInfo.rebuildModeDataShareByEdit(modedatacreater, formmodeid, id);
//							//添加置顶计算
//							String formid = modeComInfo.getFormId(formmodeid+"");
//							String tablename = workflowBillComInfo.getTablename(formid);
//							paramsForTop.put("id",id+"");//表单数据id
//							paramsForTop.put("formid",formid);//表单id
//							paramsForTop.put("tablename",tablename);//表单名称
//							paramsForTop.put("formmodeid",formmodeid+"");//表单模块id
//							SaveConditionUtil.buildTopDataDmlUpdate(paramsForTop);
//
//
//							//判断密级字段
//							Map<String,Object> params = new HashMap<>();
//							params.put("billid",id+"");
//							params.put("billtablename",tablename);
//							params.put("formId",formid);
//							params.put("formmodeid",formmodeid);
//							params.put("userId",user.getUID());
//
//							AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil();
//							addSeclevelUtil.updateSeclevelForDML(params);

						}
					}
				}

				//设置置顶数据
				for(int i=0;i<topSqlList.size();i++){
					String querySql = topSqlList.get(i);
					rs1.executeSql(querySql);
					while(rs1.next()){
						int id = rs1.getInt("id");
						int formmodeid = rs1.getInt("formmodeid");
						int modedatacreater = rs1.getInt("modedatacreater");
						if(formmodeid>0){
							//添加置顶计算
							String formid = modeComInfo.getFormId(formmodeid+"");
							String tablename = workflowBillComInfo.getTablename(formid);
							paramsForTop.put("id",id+"");//表单数据id
							paramsForTop.put("formid",formid);//表单id
							paramsForTop.put("tablename",tablename);//表单名称
							paramsForTop.put("formmodeid",formmodeid+"");//表单模块id
							SaveConditionUtil.buildTopDataDmlUpdate(paramsForTop);
						}
					}
				}

				//设置密级数据
				for(int i=0;i<seclevelSqlList.size();i++){
					String querySql = seclevelSqlList.get(i);
					rs1.executeSql(querySql);
					while(rs1.next()){
						int id = rs1.getInt("id");
						int formmodeid = rs1.getInt("formmodeid");
						int modedatacreater = rs1.getInt("modedatacreater");
						if(formmodeid>0){
							String formid = modeComInfo.getFormId(formmodeid+"");
							String tablename = workflowBillComInfo.getTablename(formid);


							//判断密级字段
							Map<String,Object> params = new HashMap<>();
							params.put("billid",id+"");
							params.put("billtablename",tablename);
							params.put("formId",formid);
							params.put("formmodeid",formmodeid);
							params.put("userId",user.getUID());

							AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil();
							addSeclevelUtil.updateSeclevelForDML(params);

						}
					}
				}


				for (int i = 0; i < rightList.size(); i++) {
					String val = rightList.get(i);
					String[] arr = val.split("_");
					if(arr.length==3){
						int modedatacreater = Util.getIntValue(arr[0]);
						int formmodeid = Util.getIntValue(arr[1]);
						int id = Util.getIntValue(arr[2]);
						if(formmodeid>0&&modedatacreater>0){
							modeRightInfo.rebuildModeDataShareByEdit(modedatacreater, formmodeid, id);
							writeLog("完成权限重构-id:"+id);
//							//添加置顶计算
//							String formid = modeComInfo.getFormId(formmodeid+"");
//							String tablename = workflowBillComInfo.getTablename(formid);
//							paramsForTop.put("id",id+"");//表单数据id
//							paramsForTop.put("formid",formid);//表单id
//							paramsForTop.put("tablename",tablename);//表单名称
//							paramsForTop.put("formmodeid",formmodeid+"");//表单模块id
//							SaveConditionUtil.buildTopDataDmlUpdate(paramsForTop);
//
//							//判断密级字段
//							Map<String,Object> params = new HashMap<>();
//							params.put("billid",id+"");
//							params.put("billtablename",tablename);
//							params.put("formId",formid);
//							params.put("formmodeid",formmodeid);
//							params.put("userId",user.getUID());
//							AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil();
//							addSeclevelUtil.updateSeclevelForDML(params);

						}
					}
				}


				//设置置顶数据
				for (int i = 0; i < topList.size(); i++) {
					String val = topList.get(i);
					String[] arr = val.split("_");
					if(arr.length==3){
						int modedatacreater = Util.getIntValue(arr[0]);
						int formmodeid = Util.getIntValue(arr[1]);
						int id = Util.getIntValue(arr[2]);
						if(formmodeid>0){
							//添加置顶计算
							String formid = modeComInfo.getFormId(formmodeid+"");
							String tablename = workflowBillComInfo.getTablename(formid);
							paramsForTop.put("id",id+"");//表单数据id
							paramsForTop.put("formid",formid);//表单id
							paramsForTop.put("tablename",tablename);//表单名称
							paramsForTop.put("formmodeid",formmodeid+"");//表单模块id
							SaveConditionUtil.buildTopDataDmlUpdate(paramsForTop);
						}
					}
				}



				//设置密级数据
				for (int i = 0; i < seclevelList.size(); i++) {
					String val = seclevelList.get(i);
					String[] arr = val.split("_");
					if(arr.length==3){
						int modedatacreater = Util.getIntValue(arr[0]);
						int formmodeid = Util.getIntValue(arr[1]);
						int id = Util.getIntValue(arr[2]);
						if(formmodeid>0){
							String formid = modeComInfo.getFormId(formmodeid+"");
							String tablename = workflowBillComInfo.getTablename(formid);
							//判断密级字段
							Map<String,Object> params = new HashMap<>();
							params.put("billid",id+"");
							params.put("billtablename",tablename);
							params.put("formId",formid);
							params.put("formmodeid",formmodeid);
							params.put("userId",user.getUID());
							AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil();
							addSeclevelUtil.updateSeclevelForDML(params);

						}
					}
				}




				//更新最后修改人以及时间
				List<Integer> updateids = (List<Integer>) updateDataMap.get("updateids");
				String tableneme = Util.null2String(updateDataMap.get("tablename"));
				if(updateids!=null){	
					if(updateids.size()>0 && "".equals(datasourceid)){
						//更新最后修改人和修改时间
						ModeDataIdUpdate modeDataIdUpdate = new ModeDataIdUpdate();
						RecordSet rSet = new RecordSet();
						String modifydatatime = DateHelper.getCurrentDate()+" "+DateHelper.getCurrentTime();
						modeDataIdUpdate.updateModifyInfo(tableneme);
						for(int billid : updateids){
							if(billid>0){
								//更新最后修改人和最后修改时间
								String sql = "update "+tableneme+" set modedatamodifier=?,modedatamodifydatetime=? where id=?";
								rSet.executeUpdate(sql, user.getUID(),modifydatatime,billid);
							}
						}
					}
				}

			}
			catch(Exception e)
			{
				writeLog("关闭连接出错 e : "+e);
			}
		}
	}

	public boolean isString(String fieldname){
	    boolean isString = true;
        for(Property [] props : propertiesList){
            for (int j = 0; j < props.length; j++){
                if(fieldname.toLowerCase().equals(props[j].getName().toLowerCase()) ){
                    String type = Util.null2String(props[j].getType());
                    if(type.equalsIgnoreCase("int")||type.equalsIgnoreCase("int(11)")||type.startsWith("decimal")){
                        return false;
                    }else{
                        return true;
                    }
                }
            }
        }
	    return isString;
    }
	/**
	 * 处理insert中包含逗号的数据
	 * @param str
	 * @return yutao add
	 */
	private List splitSqlValue(String str){
		//以逗号分隔数据
		final String[] split = str.split(",");

		List<String> stringList = new ArrayList<String>();

		//临时值存储、例如 '0,1,2,3' 字符串中包含,的参数值
		String temp = "";

		try {
			for (final String one : split) {

				final int oneLength = one.length();

				//是否以 ' 开始或者结束 boolean 值
				final boolean isStartSingleQuotes = one.indexOf("'") == 0;
				final boolean isEndSingleQuotes = one.lastIndexOf("'") == oneLength - 1;

				//如果当前不是处理'0,1,2,3'的数据
				if (!temp.isEmpty()) {
					//如果以 ' 结束 表示追加数据完毕，否则继续添加
					if (isEndSingleQuotes) {
						temp += "," + one;
						final String substring = temp.substring(1, temp.length() - 1);
						stringList.add(substring);
						temp = "";
					} else {
						temp += "," + one;
					}
					continue;
				}

				//如果以'开始，判断是否以'结束，如果是表示是字符串
				//否则为 '1,2,3'类似的参数值记录到临时 temp String 中
				if (isStartSingleQuotes) {
					if (isEndSingleQuotes) {
						final String substring = one.substring(1, oneLength - 1);
						stringList.add(substring);
					} else {
						temp += one;
					}
				} else {
					stringList.add(one);
				}
			}
		} catch (Exception e) {
			writeLog(e);
		}
		return stringList;
	}
	/**
	 * 把要执行的dmlsql变为select语句用来执行完毕后，更新权限用
	 * @param dmltype
	 * @param dmlsql  要执行的dmlsql
	 * @param connStatement
	 * @return
	 */
	private String getQuerySql(String dmltype, String dmlsql,List fieldvalueList) {
		String querySql = "";
		if(dmltype.equals("update")){
			String lowserDmlsql = dmlsql.toLowerCase();
			String keyStr = "";
			keyStr = "update";
			int index = lowserDmlsql.indexOf(keyStr);
			String tablenname = lowserDmlsql.substring(index+keyStr.length());
			keyStr = "set";
			index = tablenname.indexOf(keyStr);
			tablenname = tablenname.substring(0,index).trim();
			querySql = "select * from "+tablenname+" "+lowserDmlsql.substring(lowserDmlsql.indexOf("where"));
		}else if(dmltype.equals("insert")){
			String lowserDmlsql = dmlsql.toLowerCase();
			String keyStr = "";
			keyStr = "into";
			int index = lowserDmlsql.indexOf(keyStr);
			String tablenname = lowserDmlsql.substring(index+keyStr.length());
			keyStr = "(";
			index = tablenname.indexOf(keyStr);
			tablenname = tablenname.substring(0,index).trim();
//			String fieldStr = lowserDmlsql.substring(lowserDmlsql.indexOf("(")+1);
//			fieldStr = fieldStr.substring(0,fieldStr.indexOf(")"));
//			String[] arr = fieldStr.split(",");
//			fieldStr = "";
//			for(int i=0;i<arr.length;i++){
//				if(fieldvalueList.get(i).equals("")){
//					fieldStr+= " ("+arr[i]+" like ? or "+arr[i]+" is null) ";
//				}else{
//					fieldStr+= arr[i]+" like ? ";
//				}
//				if(i<arr.length-1){
//					fieldStr += " and ";
//				}
//			}
//			if(!fieldStr.equals("")){
//				fieldStr = fieldStr.substring(0,fieldStr.length()-1);
//			}
			querySql = "select max(id) as id from "+tablenname;
		}
		return querySql;
	}

	/**
	 * 执行sql
	 * @param connStatementDataSource
	 * @param connStatement
	 * @param sql
	 * @param fieldtypeList
	 * @param fieldvalueList
	 */
	private void executesql(String dbtype,ConnStatementDataSource connStatementDataSource,ConnStatement connStatement,String sql,List fieldtypeList,List fieldvalueList)
	{
		try
		{
			writeLog("执行sql : "+sql);
			//添加sql判断 是否是插入语句insert

			//if(sql.indexOf("insert") !=-1 && isNeedModeUuid(sql)){
			//	//执行sql重构
			//	sql = getSqlWithUuid(sql);
			//
			//}
			if(null!=connStatementDataSource)
			{
				connStatementDataSource.setStatementSql(sql);
			}
			else if(null!=connStatement)
			{
				connStatement.setStatementSql(sql);
			}
			if(null!=fieldtypeList&&fieldtypeList.size()>0)
			{
				for(int i = 0;i<fieldtypeList.size();i++)
				{
					String fielddbtype = (String)fieldtypeList.get(i);
					String fieldvalue = (String)fieldvalueList.get(i);
					boolean ischeck = DBTypeUtil.checkFieldDBType(fielddbtype, dbtype);
					String settype = DBTypeUtil.getThistype();
					writeLog("dbtype : "+ dbtype +"  fielddbtype : "+fielddbtype+" fieldvalue : "+fieldvalue+"  settype : "+settype);
					this.setValueWithDBTypeInStatment(i+1, connStatementDataSource, connStatement, settype, fieldvalue);
				}
			}
			if(null!=connStatementDataSource)
			{
				connStatementDataSource.executeUpdate();
			}
			else if(null!=connStatement)
			{
				connStatement.executeUpdate();
			}


		}
		catch(Exception e)
		{
			writeLog("执行sql出错 e : ");
			writeLog(e);
			dmlResult.put("flag", "false");
		}
	}
	/**
	 * 将数据填充至statment中
	 * @param connStatementDataSource
	 * @param connStatement
	 * @param settype
	 * @param fieldvalue
	 * @throws Exception
	 */
	private void setValueWithDBTypeInStatment(int index,ConnStatementDataSource connStatementDataSource,ConnStatement connStatement,String settype,String fieldvalue) throws Exception
	{

		//setString 1
		//setInt 2
		//setFloat 3
		//setDate 4
		//setBigDecimal 5
		//setBinaryStream 6
		//setBytes 7
		//setCharacterStream 8
		//setObject 9
		//setNull 10
		//setClob 11
		//setBlob 12
		if(null!=connStatementDataSource)
		{
			if("1".equals(settype))
			{
				connStatementDataSource.setString(index, fieldvalue);
			}
			else if("2".equals(settype))
			{
				connStatementDataSource.setInt(index, Util.getIntValue(fieldvalue,0));
			}
			else if("3".equals(settype))
			{
			    if(fieldvalue == null){
                    connStatementDataSource.setString(index, fieldvalue);
                }else{
			        connStatementDataSource.setFloat(index, Util.getFloatValue(fieldvalue,0));
                }
			}
			else if("4".equals(settype))
			{
				java.sql.Date date = null;
				try
				{
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					Date dt = sdf.parse(fieldvalue);
					date = new java.sql.Date(dt.getTime());
				}
				catch(Exception e)
				{
					writeLog("转换日期型出错 ： fieldvalue : "+fieldvalue);
				}
				connStatementDataSource.setDate(index, date);
			}
			else if("5".equals(settype))
			{
				BigDecimal fieldvalueb = null;
				try
				{
					fieldvalueb = new BigDecimal(fieldvalue);
				}
				catch(Exception e)
				{
					writeLog("转换数值型出错 ： fieldvalue : "+fieldvalue);
				}
//				if(null == fieldvalueb)
//				{
//					fieldvalueb = new BigDecimal("0");
//				}
				connStatementDataSource.setBigDecimal(index, fieldvalueb);
			}
			else if("6".equals(settype))
			{
				connStatementDataSource.setBinaryStream(index, null,0);
			}
			else if("7".equals(settype))
			{
				connStatementDataSource.setBytes(index, fieldvalue.getBytes());
			}
			else if("8".equals(settype))
			{
				connStatementDataSource.setCharacterStream(index, fieldvalue);
			}
			else if("9".equals(settype))
			{
				connStatementDataSource.setObject(index, null);
			}
			else if("10".equals(settype))
			{
				//connStatementDataSource.setNull(index);
				if("".equals(fieldvalue)){
					fieldvalue = null;
				}
				connStatementDataSource.setString(index, fieldvalue);
			}
			else if("11".equals(settype))
			{
				connStatementDataSource.setClob(index, null);
			}
			else if("12".equals(settype))
			{
				connStatementDataSource.setBlob(index, null);
			}
		}
		if(null!=connStatement)
		{
			if("1".equals(settype))
			{
				connStatement.setString(index, fieldvalue);
			}
			else if("2".equals(settype))
			{
				connStatement.setInt(index, fieldvalue);
			}
			else if("3".equals(settype))
			{
                if(fieldvalue == null){
                    connStatementDataSource.setString(index, fieldvalue);
                }else{
                    connStatementDataSource.setFloat(index, Util.getFloatValue(fieldvalue,0));
                }
			}
			else if("4".equals(settype))
			{
				java.sql.Date date = null;
				try
				{
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					Date dt = sdf.parse(fieldvalue);
					date = new java.sql.Date(dt.getTime());
				}
				catch(Exception e)
				{
					writeLog("转换日期型出错 ： fieldvalue : "+fieldvalue);
				}
				connStatement.setDate(index, date);
			}
			else if("5".equals(settype))
			{
				BigDecimal fieldvalueb = null;
				try
				{
					fieldvalueb = new BigDecimal(fieldvalue);
				}
				catch(Exception e)
				{
					writeLog("转换数值型出错 ： fieldvalue : "+fieldvalue);
				}
//				if(null == fieldvalueb)
//				{
//					fieldvalueb = new BigDecimal("0");
//				}
				connStatement.setBigDecimal(index, fieldvalueb);
			}
			else if("6".equals(settype))
			{
				connStatement.setBinaryStream(index, null,0);
			}
			else if("7".equals(settype))
			{
				connStatement.setBytes(index, fieldvalue.getBytes());
			}
			else if("8".equals(settype))
			{
				connStatement.setCharacterStream(index, fieldvalue);
			}
			else if("9".equals(settype))
			{
				connStatement.setObject(index, null);
			}
			else if("10".equals(settype))
			{
				if("".equals(fieldvalue)){
					fieldvalue = null;
				}
//				connStatement.setNull(index);
				connStatement.setString(index, fieldvalue);
			}
			else if("11".equals(settype))
			{
				connStatement.setClob(index, null);
			}
			else if("12".equals(settype))
			{
				connStatement.setBlob(index, null);
			}
		}
	}


	/**
	 * 动态增加数组长度
	 * @param array
	 * @param newSize
	 * @return
	 */
	public Object expand(Object array, int newSize) {

		if (array == null) {

			return null;

		}

		Class c = array.getClass();

		if (c.isArray()) {

			int len = Array.getLength(array);

			if (len >= newSize) {

				return array;

			} else {

				Class cc = c.getComponentType();

				Object newArray = Array.newInstance(cc, newSize);

				System.arraycopy(array, 0, newArray, 0, len);

				return newArray;

			}

		} else {

			// throw new ClassCastException("need  array");
			return array;

		}

	}

	/**
	 * 获取更新的表单信息
	 * @param ids
	 * @param rs
	 * @param dmltype
	 * @param dmlsql
	 * @param fieldtypeList
	 * @param datasourceid
	 * @return
	 */
	public Map<String,Object> getUpdateDatas(List<Integer> ids,RecordSet rs,String dmltype,String dmlsql,List fieldtypeList,String datasourceid){
		Map<String,Object> res = new HashedMap();
		String querySql = getQuerySql(dmltype, dmlsql,fieldtypeList);
		if(!"".equals(querySql)){
			String tablename = querySql.substring(querySql.indexOf("from")+4,querySql.indexOf("where")).trim();
			//根据tablename获取formid
			String sqlForTableName = " select id from workflow_bill where tablename = '"+tablename+"'";
			rs.execute(sqlForTableName);
			while (rs.next()){
				res.put("formId",Util.null2String(rs.getString("id"),""));
			}
			res.put("ids",ids);
			res.put("tablename",tablename);

		}
		return res;
	}

	/**
	 * 获取表名称
	 * @param dmlsql
	 * @return
	 */
	public String getTableName(String dmlsql) {
		String tablenname = "";
		if (!"".equals(dmlsql)) {
			String lowserDmlsql = dmlsql.toLowerCase();
			String keyStr = "";
			keyStr = "into";
			int index = lowserDmlsql.indexOf(keyStr);
			tablenname = lowserDmlsql.substring(index + keyStr.length());
			keyStr = "(";
			index = tablenname.indexOf(keyStr);
			tablenname = tablenname.substring(0, index).trim();
		}
		return tablenname;
	}

	/**
	 * 拼接sql 添加uuid 一列
	 * @param sql
	 * @return
	 */
	public String getSqlWithUuid(String sql){
		String resultSql = "";
		String modeuuid = UUID.randomUUID().toString();
		int count = sql.indexOf(")");
		String tepmSqlOne= sql.substring(0,count)+",modeuuid";
		String tempSqlTwo = sql.substring(count,sql.length()-1)+",?)";
		resultSql = tepmSqlOne+tempSqlTwo;
		//dmlcussqlvalue.add(modeuuid);
		return resultSql;
	}

	public Boolean isNeedModeUuid(String sql){
		String tablename = getTableName(sql);
		RecordSet rs = new RecordSet();
		boolean flag = rs.executeQuery("select count(1) from "+tablename+" where modeuuid is not null");
		return flag;
	}

}